package com.bfly.common.json;

import org.json.JSONObject;
import org.json.XML;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * xml操作工具类
 *
 * @author 长沙商脉科技有限公司
 * @date 2018/12/6 16:05
 */
public class JaxbUtil {

    /**
     * XML转JSON
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/12/11 21:40
     */
    public static com.alibaba.fastjson.JSONObject xmlToJson(String xml) {
        JSONObject json = XML.toJSONObject(xml);
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject(json.toMap());
        return jsonObject;
    }

    /**
     * Json转为XML
     *
     * @author 长沙商脉科技有限公司
     * @date 2021/1/7 23:34
     */
    public static String jsonToXml(com.alibaba.fastjson.JSONObject json) {
        JSONObject jsonObject = new JSONObject(json.toJSONString());
        String xml = XML.toString(jsonObject);
        return xml;
    }

    /**
     * 对象转为字符串
     *
     * @author 长沙商脉科技有限公司
     * @date 2018/12/6 16:05
     */
    public static String toXml(Object obj) {
        try {
            StringWriter writer = new StringWriter();
            JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            marshaller.marshal(obj, writer);
            return writer.toString();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 转为对象
     *
     * @author 长沙商脉科技有限公司
     * @date 2018/12/6 16:05
     */
    public static <T> T toObject(String xml, Class<T> cls) {
        try {
            StringReader reader = new StringReader(xml);
            JAXBContext jaxbContext = JAXBContext.newInstance(cls);
            return (T) jaxbContext.createUnmarshaller().unmarshal(reader);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
}
